package com.pipi.fanglan.ui.controller;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.pipi.fanglan.cookie.CookieRepository;
import com.pipi.fanglan.dao.CommitOrderDao;
import com.pipi.fanglan.dao.OrderDao;
import com.pipi.fanglan.dao.UserDao;
import com.pipi.fanglan.httpproxy.LoginProxy;
import com.pipi.fanglan.model.MyCookieStore;
import com.pipi.fanglan.model.User;
import com.pipi.fanglan.model.WorkOrder;
import com.pipi.fanglan.model.form.ConfirmOrderForm;
import com.sun.jndi.toolkit.url.Uri;
import org.apache.commons.logging.LogFactory;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

/**
 * Created by pipi on 2017/7/15.
 */
@Controller
@RequestMapping("/monitor")
public class LoginController {
    String hostUrl = "http://111.21.17.28:10001/partner";
    String domain = "111.21.17.28";

    @Autowired
    private CookieRepository cookieRepository;

    @Autowired
    public OrderDao orderDao;

    @Autowired
    public UserDao userDao;

    @Autowired
    public CommitOrderDao commitOrderDao;

    @GetMapping("/login")
    public String login() throws Exception{
        return "monitor/login";
    }

    @PostMapping("/RSAKey")
    @ResponseBody
    public String getRsa(String userName) throws Exception{
        CookieStore cookieStore = LoginProxy.saveCookieStore(hostUrl);
        MyCookieStore myCookieStore = new MyCookieStore();
        myCookieStore.setUserName(userName);
        myCookieStore.setCookieStore(cookieStore);
        cookieRepository.save(myCookieStore);
        String result1 = LoginProxy.defaultPost(hostUrl+ "/RSAKey",new ArrayList<NameValuePair>(),cookieStore);
        return result1;
    }

    @PostMapping("/loginPost")
    @ResponseBody
    public String loginPost(String userName, String password,String realName) throws Exception{
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        NameValuePair userNamePair= new BasicNameValuePair("j_username",userName);
        NameValuePair passwordPair= new BasicNameValuePair("j_password",password);
        nvps.add(userNamePair);
        nvps.add(passwordPair);
        MyCookieStore myCookieStore = cookieRepository.findMyCookieStore(realName);
        String result = LoginProxy.defaultPost(hostUrl + "/index.do?method=saveSession",nvps,myCookieStore.getCookieStore());
        User user = userDao.getUser(result);
        String login = "false";
        if(user.getUserName() != null && !"".equals(user.getUserName())){
            MyCookieStore activeCookieStore = cookieRepository.findActive();
            if(activeCookieStore != null){
                activeCookieStore.setActive(false);
            }
            myCookieStore.setActive(true);
            login = "ok";
        }
        return login;
    }

    @GetMapping("/logout")
    public String logout(){
        MyCookieStore cookieStore = cookieRepository.findActive();
        cookieStore.setActive(false);
        MyCookieStore cookieStore1 = cookieRepository.findAll().get(0);
        if(cookieStore1 != null){
            cookieStore1.setActive(true);
        }
        return "redirect:/monitor/login";
    }

    @GetMapping("/list")
    public String list(Model model) throws  Exception{
        MyCookieStore cookieStore = cookieRepository.findActive();
        List<WorkOrder> orders = null;
        if(cookieStore !=null){
            String result = LoginProxy.defautGet(hostUrl + "/sheet/pnrfaultdeal/pnrfaultdeal.do?method=showListsendundo",cookieStore.getCookieStore());
            orders =  orderDao.orderList(result);
            model.addAttribute("orders",orders);
        }
        if(orders == null){
            model.addAttribute("orders",new ArrayList<WorkOrder>());
        }
        List<MyCookieStore> cookieStoreList = cookieRepository.findAll();
        model.addAttribute("users", cookieStoreList != null?cookieStoreList:new ArrayList<MyCookieStore>());
        return "monitor/list";
    }

    @GetMapping("/detail")
    @ResponseBody
    public String detail(String param) throws Exception {
        String url2 = hostUrl + "/sheet/pnrfaultdeal/" + param;
        MyCookieStore cookieStore = cookieRepository.findActive();
        CookieStore cookieStore1 = cookieStore.getCookieStore();
//        String url2 = "http://111.21.17.28:10001/partner/sheet/pnrfaultdeal/pnrfaultdeal.do?method=showDealPage&sheetKey=ff8080815d3df6ad015d4b544a007eba&piid=_PI%3a9003015d.4b544a82.fa3732f5.9053350d&taskId=_TKI%3aa01b015d.4b54ce41.fa3732f5.90533a76&taskName=FaultDealTask&operateRoleId=&TKID=_TKI%3aa01b015d.4b54ce41.fa3732f5.90533a76&taskStatus=8&preLinkId=ff8080815d3df6ad015d4b544a297ebc&operateType=95";
        String detaiHtml = LoginProxy.defautGet(url2,cookieStore1);

//        File fileText1 = new File("jiedan1.txt");
//        FileWriter fileWriter1 = new FileWriter(fileText1);
//        fileWriter1.write(result);
//        fileWriter1.close();
        String commitFormHtmlUrl = commitOrderDao.getCommitFormUrl(detaiHtml);

        String commitFormHtml =  LoginProxy.defautGet(hostUrl + "/sheet/pnrfaultdeal/"+commitFormHtmlUrl,cookieStore1);
//        File fileText = new File("jiedan.txt");
//        FileWriter fileWriter = new FileWriter(fileText);
//        fileWriter.write(form);
//        fileWriter.close();

        ConfirmOrderForm orderForm = commitOrderDao.getCommitParams(commitFormHtml);
        Uri uri = new Uri(url2);
        String performClaimTaskUrl = uri.getScheme()+ "://" + uri.getHost() + ":" + uri.getPort() + orderForm.getPerformClaimTaskUrl();
        String preCommitResult = LoginProxy.defaultPost(performClaimTaskUrl,orderForm.getParams(),cookieStore1);

        File preCommitText = new File("preCommitResult.txt");
        FileWriter fileWriter = new FileWriter(preCommitText);
        fileWriter.write(preCommitResult);
        fileWriter.close();

        String commitUrl = uri.getScheme()+ "://" + uri.getHost() + ":" + uri.getPort() + orderForm.getUrl();
        String commitResult = LoginProxy.defaultPost(commitUrl,orderForm.getParams(),cookieStore1);

        File commitText = new File("commitResult.txt");
        FileWriter commitfileWriter = new FileWriter(commitText);
        commitfileWriter.write(commitResult);
        commitfileWriter.close();
//        boolean operaFlag = commitOrderDao.checkCommitSuccess(commitResult);
        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log",
                "org.apache.commons.logging.impl.NoOpLog");
        java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
//支持JavaScript
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setTimeout(5000);
        HtmlPage rootPage = webClient.getPage(url2);
        CookieManager cookieManager = new CookieManager();
//        cookieManager.addCookie(cookieStore1.getCookies().get(0));
//        webClient.setCookieManager();
//设置一个运行JavaScript的时间
        webClient.waitForBackgroundJavaScript(5000);
//        webClient.setPageCreator();
        String html = rootPage.asXml();
        Document document = Jsoup.parse(html);
        return commitUrl;
    }

    @GetMapping("/commit")
    public String commitFault(){
        return "redirect:/monitor/list";
    }

}
